package com.itphy.util;

import com.itphy.conf.FastDFSProperties;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.Objects;

public class FastDFSClient {

    private TrackerClient trackerClient = null;
    private TrackerServer trackerServer = null;
    private StorageServer storageServer = null;
    private StorageClient1 storageClient = null;


    public FastDFSClient()  {
        try {
            trackerClient = new TrackerClient();
            trackerServer = trackerClient.getConnection();
            storageServer = null;
            storageClient = new StorageClient1(trackerServer, storageServer);
        }catch (Exception e){
            throw new RuntimeException("FastDFS初始化失败");
        }
    }

    /**
     * fastdfs 初始化
     * @param dfs
     * @throws FileNotFoundException
     * @throws IOException
     * @throws Exception
     */
    public static void init(FastDFSProperties dfs) throws FileNotFoundException, IOException, Exception {
        ClientGlobal.g_connect_timeout = getVal(dfs.connect_timeout, 5);
        if (ClientGlobal.g_connect_timeout < 0) {
            ClientGlobal.g_connect_timeout = 5;
        }

        ClientGlobal.g_connect_timeout *= 1000;
        ClientGlobal.g_network_timeout = getVal(dfs.network_timeout, 30);
        if (ClientGlobal.g_network_timeout < 0) {
            ClientGlobal.g_network_timeout = 30;
        }

        ClientGlobal.g_network_timeout *= 1000;
        ClientGlobal.g_charset = getVal(dfs.charset,null);
        if (ClientGlobal.g_charset == null || ClientGlobal.g_charset.length() == 0) {
            ClientGlobal.g_charset = "ISO8859-1";
        }

        String[] szTrackerServers = null;
        if(!Objects.isNull(dfs.tracker_server)){
            szTrackerServers = dfs.tracker_server.split("\\,");
        }
        if (szTrackerServers == null) {
            throw new Exception("请配置 tracker_server ！");
        } else {
            InetSocketAddress[] tracker_servers = new InetSocketAddress[szTrackerServers.length];

            for (int i = 0; i < szTrackerServers.length; ++i) {
                String[] parts = szTrackerServers[i].split("\\:", 2);
                if (parts.length != 2) {
                    throw new Exception(" tracker_server 的值无效，正确的格式为host：port");
                }

                tracker_servers[i] = new InetSocketAddress(parts[0].trim(), Integer.parseInt(parts[1].trim()));
            }

            ClientGlobal.g_tracker_group = new TrackerGroup(tracker_servers);
            ClientGlobal.g_tracker_http_port = getVal(dfs.g_tracker_http_port, 80);
            ClientGlobal.g_anti_steal_token = getVal(dfs.g_anti_steal_token, false);
            if (ClientGlobal.g_anti_steal_token) {
                ClientGlobal.g_secret_key = getVal(dfs.g_secret_key,null);
            }

        }
    }

    public static  <T> T getVal(T t, T t2) {
        if (Objects.isNull(t)) {
            return t2;
        }
        return t;
    }


    /**
     * 上传文件方法
     * <p>Title: uploadFile</p>
     * <p>Description: </p>
     * @param fileName 文件全路径
     * @param extName 文件扩展名，不包含（.）
     * @param metas 文件扩展信息
     * @return
     * @throws Exception
     */
    public String uploadFile(String fileName, String extName, NameValuePair[] metas) throws Exception {
        String result = storageClient.upload_file1(fileName, extName, metas);
        return result;
    }

    public String uploadFile(String fileName) throws Exception {
        return uploadFile(fileName, null, null);
    }

    public String uploadFile(String fileName, String extName) throws Exception {
        return uploadFile(fileName, extName, null);
    }

    /**
     * 上传文件方法
     * <p>Title: uploadFile</p>
     * <p>Description: </p>
     * @param fileContent 文件的内容，字节数组
     * @param extName 文件扩展名
     * @param metas 文件扩展信息
     * @return
     * @throws Exception
     */
    public String uploadFile(byte[] fileContent, String extName, NameValuePair[] metas) throws Exception {
        String result = storageClient.upload_file1(fileContent, extName, metas);
        return result;
    }

    public String uploadFile(byte[] fileContent) throws Exception {
        return uploadFile(fileContent, null, null);
    }

    public String uploadFile(byte[] fileContent, String extName) throws Exception {
        return uploadFile(fileContent, extName, null);
    }
}
